package com.atguigu.tingshu.album.receiver;

import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.album.service.TrackInfoService;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.vo.album.TrackStatMqVo;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author atguigu-mqx
 * @ClassName TrackReceiver
 * @description: TODO
 * @date 2025年03月03日
 * @version: 1.0
 */
@Component
public class TrackReceiver {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private TrackInfoService trackInfoService;

    /**
     * 监听消息
     * @param msg
     * @param message
     * @param channel
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_TRACK_STAT_UPDATE,durable = "true",autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_TRACK),
            key = MqConst.ROUTING_TRACK_STAT_UPDATE
    ))
    public void updateTrackStat(String msg, Message message, Channel channel){
        //  判断消息是否正确发送过来
        if (!StringUtils.isEmpty(msg)){
            //  消息类型属于;TrackStatMqVo 这个实体;
            TrackStatMqVo trackStatMqVo = JSON.parseObject(msg, TrackStatMqVo.class);
            //  使用businessNo 属性去重，防止消息重复消费!
            String businessNo = trackStatMqVo.getBusinessNo();
            Boolean result = redisTemplate.opsForValue().setIfAbsent("trackStat:" + businessNo, businessNo, 10, TimeUnit.MINUTES);
            //  判断:
            if (result){
                try {
                    //  调用服务层方法+1；
                    trackInfoService.updateTrackStat(trackStatMqVo);
                } catch (Exception e) {
                    //  删除缓存的key;
                    this.redisTemplate.delete("trackStat:" + businessNo);
                    //  记录重试次数：
                    //  channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,false);
                    throw new RuntimeException(e);
                }
            }
        }
        //  手动确认
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}
